import router, { asyncRouterMap, constantRouterMap } from '@/router'
import {
    flatMultiLevelRoutes,
    generateRoutesByFrontEnd,
    generateRoutesByServer,
} from '@/router/routerHelper'
import { store } from '@fl/store/index'
import { cloneDeep } from 'lodash-es'
import { defineStore } from 'pinia'

export type PermissionState = {
    addRouters: AppRouteRecordRaw[]
    isAddRouters: boolean
    menuTabRouters: AppRouteRecordRaw[]
    // siderbar 菜单路径前缀
    pathPrefix: string
    routers: AppRouteRecordRaw[]
    // 大系统下的分片路由
    sliceRouters: AppRouteRecordRaw[]
}

// 根据角色设置路由
type IOptions = {
    isAdmin?: boolean
}

export const usePermissionStore = defineStore('permission', {
    actions: {
        generateRoutes(
            type: 'frontEnd' | 'server' | 'static',
            routers?: AppCustomRouteRecordRaw[] | string[],
            options: IOptions = {},
        ): Promise<unknown> {
            return new Promise<void>((resolve) => {
                let routerMap: AppRouteRecordRaw[] = []
                if (type === 'server') {
                    // 模拟后端过滤菜单
                    routerMap = generateRoutesByServer(routers as AppCustomRouteRecordRaw[], options)
                }
                else if (type === 'frontEnd') {
                    // 模拟前端过滤菜单
                    routerMap = generateRoutesByFrontEnd(cloneDeep(asyncRouterMap), routers as string[])
                }
                else {
                    // 直接读取静态路由表
                    routerMap = cloneDeep(asyncRouterMap)
                }
                // 动态路由，404一定要放到最后面
                this.addRouters = routerMap.concat([
                    {
                        meta: {
                            breadcrumb: false,
                            hidden: true,
                        },
                        name: '404Page',
                        path: '/:path(.*)*',
                        redirect: '/404',
                    },
                ])
                // 渲染菜单的所有路由
                this.routers = cloneDeep(constantRouterMap).concat(routerMap)
                resolve()
            })
        },
        setIsAddRouters(state: boolean): void {
            this.isAddRouters = state
        },
        setMenuTabRouters(routers: AppRouteRecordRaw[]): void {
            this.menuTabRouters = routers
        },
        // 设置分片的路由
        setSliceRouters(path?: string): void {
            if (path) {
                this.pathPrefix = path

                const target = this.getRouters.find(item => item.path === path)
                this.sliceRouters = target?.children ?? []
                router.push(path)
            }
        },
    },
    getters: {
        getAddRouters(): AppRouteRecordRaw[] {
            return flatMultiLevelRoutes(cloneDeep(this.addRouters))
        },
        getIsAddRouters(): boolean {
            return this.isAddRouters
        },
        getMenuTabRouters(): AppRouteRecordRaw[] {
            return this.menuTabRouters
        },
        getPathPrefix(): string {
            return this.pathPrefix
        },
        getRouters(): AppRouteRecordRaw[] {
            return this.routers
        },
        getSliceRouters(): AppRouteRecordRaw[] {
            return this.sliceRouters
        },
    },
    persist: {
        paths: ['routers', 'addRouters', 'menuTabRouters'],
    },
    state: (): PermissionState => ({
        addRouters: [],
        isAddRouters: false,
        menuTabRouters: [],
        pathPrefix: '',
        routers: [],
        // 大系统下的分片路由
        sliceRouters: [],
    }),
})

export function usePermissionStoreWithOut() {
    return usePermissionStore(store)
}
